using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;

namespace ScheduleParserWorkerRole
{
    public class DataExpirationManager
    {
        private readonly Dictionary<string, DateTime> _expirationTimeouts = new Dictionary<string, DateTime>();

        public bool IsExpired(string iKey)
        {
            if (!_expirationTimeouts.ContainsKey(iKey))
            {
                return true;
            }
            if (_expirationTimeouts[iKey] < DateTime.UtcNow)
            {
                _expirationTimeouts.Remove(iKey);
                return true;
            }
            return false;
        }

        public void Invalidate(string iKey)
        {
            _expirationTimeouts.Remove(iKey);
        }

        public void SetValidUntil(string iKey, DateTime iValue)
        {
            if (iValue > DateTime.UtcNow)
            {
                Invalidate(iKey);
                _expirationTimeouts.Add(iKey, iValue);
            }
        }

        public DateTime GetNearestExpirationTime()
        {
            if (_expirationTimeouts.Any())
            {
                return _expirationTimeouts.Select(pair => pair.Value).Min();
            }
            else
            {
                return DateTime.UtcNow.AddSeconds(-1);
            }
        }
    }
    
}
